/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author asmaa
 */
public class RegUser extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    /*protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. 
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RegUser</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RegUser at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }*/

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    String bdate;
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        try {
            /* Connection With Database */
            PrintWriter out=response.getWriter();
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/Shopping", "root", "asmaaelmasry");
            PreparedStatement ps =  (PreparedStatement) con.prepareStatement("INSERT INTO User (name,email,password,job,interest,address,birthday,creditLimit,image) VALUES (?,?,?,?,?,?,?,?,?) ",Statement.RETURN_GENERATED_KEYS);
            /* Get Form Items */
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            
            Iterator<FileItem> iter = items.iterator();
            InputStream uploadedStream = null;
            String name="",email="" ,id="";
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("name")){
                        name = item.getString();
                        ps.setString(1, item.getString() );
                    }else if(item.getFieldName().equals("email")){
                        email = item.getString();
                        ps.setString(2, item.getString() );
                    }else if(item.getFieldName().equals("pass"))
                        ps.setString(3, item.getString() );
                    else if(item.getFieldName().equals("job"))
                        ps.setString(4, item.getString() );
                    else if(item.getFieldName().equals("interest"))
                        ps.setString(5, item.getString() );
                    else if(item.getFieldName().equals("address"))
                        ps.setString(6, item.getString() );
                    else if(item.getFieldName().equals("bdate")){
                      
                        bdate =item.getString();
                        int indD = bdate.indexOf("-");
		
                        String day =bdate.substring(0,indD);
                        
                        String mon =bdate.substring(indD+1);

                        int indM = mon.indexOf("-");
			
			String month= mon.substring(0,indM);
			int indY = mon.lastIndexOf("-");

                       String year = mon.substring(indY+1);
	
                       String bbdate=year+"-"+month+"-"+day;
		
                        ps.setString(7, bbdate);}
                    else if(item.getFieldName().equals("creditLimit")){
                        float p = 0;
                        if(RegUser.isFloat(item.getString()))
                            p = Float.parseFloat(item.getString());
                        ps.setFloat(8, p );
                        
                    }/*else if(item.getFieldName().equals("credit")){
                        int q = 0;
                        if(RegUser.isInteger(item.getString()))
                            q = Integer.parseInt(item.getString());
                        ps.setInt(9, q );
                    }*/
                }else {
                    String fileName = item.getName();
                    String contentType = item.getContentType();  
                    //boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                                        
                    if(fileName != null && !fileName.isEmpty() && sizeInBytes <= 3145728  && contentType != null && contentType.contains("image") ){
                   
                        uploadedStream = item.getInputStream();
                        ps.setBinaryStream(9, uploadedStream,(int) item.getSize());
                        
                    }else
                         ps.setString(9, "");
                }
                
            }
            
            ps.executeUpdate();
            ResultSet keyResultSet = ps.getGeneratedKeys();
            keyResultSet.next();
            id = keyResultSet.getString(1);
            if(uploadedStream != null)
                uploadedStream.close();
            
            HttpSession session = request.getSession(true);
            session.setAttribute("id", id );
            session.setAttribute("name", name);
            session.setAttribute("email", email);
			
            response.sendRedirect("index.jsp");
            
        }catch (Exception  ex) {
            Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
            
            response.sendRedirect("error.jsp");
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    public static boolean isInteger(String s) {
        try{ 
            Integer.parseInt(s); 
        }catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }
    
     public static boolean isFloat(String s) {
        try{ 
            Float.parseFloat(s); 
        }catch(NumberFormatException e) { 
            return false; 
        }
        // only got here if we didn't return false
        return true;
    }
}
